package cn.dg.manager.goods.goodsIntroduction.action;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;

import cn.dg.manager.base.BaseController;
import cn.dg.manager.base.entity.HttpResult;
import cn.dg.manager.base.util.DateUtil;
import cn.dg.manager.base.util.PageData;
import cn.dg.manager.common.entity.PageEntity;
import cn.dg.manager.goods.goodsClassify.entity.GoodsType;
import cn.dg.manager.goods.goodsClassify.service.GoodsService;
import cn.dg.manager.goods.goodsIntroduction.entity.GoodsInfoVO;
import cn.dg.manager.goods.goodsIntroduction.service.GoodsIntroductionService;

@Controller
public class GoodsIntroductionAction extends BaseController {

	@Autowired
	private GoodsIntroductionService goodsIntroductionService;
	
	@Autowired
	private GoodsService goodsService;
	
	// 上传文件最大件数
	public static final int MAX_FILE_COUNT = 3;
	
	// 上传文件基本目录
	public static final String BASE_FILE_PATH = "/uploadsFiles/goodsImage/";
	
	public static final String CREATE_GOODS_ORDER_URL = "/createGoodsOrderFacade?qrCode=";
	/**
	 * 商品详情页
	 * 
	 * @return
	 */
	@RequestMapping(value="/goodsBaseIndex")
	public String index() {
		return "goods/goodsIntroduction/main";
	}
	
	/**
	 * 商品一览部数据表示
	 * 
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/search")
	@ResponseBody
	public Object search() {
		PageData pd = this.getPageData();
		String page = pd.getString("page");
		String rows = pd.getString("rows");
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("page", page);
		condMap.put("rows", rows);
		condMap.put("typeId", pd.getString("typeId"));
		condMap.put("goodName", pd.getString("goodName"));
		
		PageEntity<GoodsInfoVO> goodsInfoList = goodsIntroductionService.getGoodsInfoListPage(condMap);
		return HttpResult.createSuccessResult(goodsInfoList, "0");
	}
	
	/**
	 * 根据主键查询数据
	 * 
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/findGoodsInfoById")
	@ResponseBody
	public Object findGoodsInfoById() {
		PageData pd = this.getPageData();
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("goodId", pd.get("goodId"));
		GoodsInfoVO vo = goodsIntroductionService.findGoodsInfoById(condMap);
		return HttpResult.createSuccessResult(vo, "0");
	}
	
	/**
	 *  新增商品信息
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/add")
	public ModelAndView add() {
		ModelAndView mv = this.getModelAndView();
		mv.addObject("mode", "0");
		mv.setViewName("goods/goodsIntroduction/detail");
		return mv;
	}
	
	/**
	 * 更新商品信息
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/update")
	public ModelAndView update() {
		ModelAndView mv = this.getModelAndView();
		// 更新
		mv.addObject("mode", "1");
		mv.setViewName("goods/goodsClassify/detail");
		return mv;
	}
	
	/**
	 * 商品图片上传
	 * @param goodId
	 * @param request
	 * @param uploadImageFile
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/addGoodsPictures", method = RequestMethod.POST)
	@ResponseBody
	public Object addGoodsPictures(String goodId, HttpServletRequest request, @RequestParam("file") MultipartFile[] uploadImageFile) {
		Map<String, Object> filePathMap = uploadFiles(goodId, request, uploadImageFile);
		if(filePathMap == null) {
			return HttpResult.createErrorResult("商品图片上传失败！", "", "-1");
		} else {
			return HttpResult.createSuccessResult(filePathMap, "0");
		}
	}
	
	/**
	 * 删除图片处理逻辑
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/delPictures", method = RequestMethod.POST)
	@ResponseBody
	public Object delPictures(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> filePathMap = delGoodsPictures(request);
		if(filePathMap == null) {
			return HttpResult.createErrorResult("商品图片删除失败！", "", "-1");
		} else {
			return HttpResult.createSuccessResult(filePathMap, "0");
		}
	}
	
	/**
	 * 删除图片处理
	 * @param request
	 * @return
	 */
	private Map<String, String> delGoodsPictures(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 商品图片上传
	 * @param goodId
	 * @param request
	 * @param uploadImageFile
	 * @return
	 */
	public Map<String, Object> uploadFiles(String goodId, HttpServletRequest request, MultipartFile[] uploadImageFile) {
		int fileCount = 0;
		Map<String, Object> filePathMap = new HashMap<String, Object>(MAX_FILE_COUNT + 1);
		String realPath = this.getRequest().getSession().getServletContext().getRealPath("");
		String fileDir = DateUtil.getDays();
		String savePath = realPath.concat(BASE_FILE_PATH).concat(fileDir);
		
		File file = new File(savePath);
		if (!file.exists()) {
			file.mkdir();
		}
		
		try {
			for (MultipartFile imageFile : uploadImageFile) {
				if (imageFile != null && !imageFile.isEmpty()) {
					String fileName = DateUtil.getSdfTimesSSS();
					String suffix = getFileSuffix(imageFile.getOriginalFilename());
					String newFilePath = File.separator.concat(fileName).concat(suffix);
					File newFile = new File(savePath.concat(newFilePath));
					imageFile.transferTo(newFile);
					if (fileCount == 0) {
						filePathMap.put("goodImage", BASE_FILE_PATH.concat(fileDir).concat(newFilePath));
					} else {
						filePathMap.put("goodImage".concat(String.valueOf(fileCount)),
								BASE_FILE_PATH.concat(fileDir).concat(newFilePath));
					}
					fileCount++;
				}
			}
			filePathMap.put("goodId", goodId);
			goodsIntroductionService.updateGoodsImageInfo(filePathMap);

		} catch (IllegalStateException e) {
			e.printStackTrace();
			filePathMap = null;
		} catch (IOException e) {
			e.printStackTrace();
			filePathMap = null;
		}
		return filePathMap;
	}
	
	/**
	 * 
	 * @param fileName
	 * @return
	 */
	public String getFileSuffix(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));  
	}
	
	/**
	 * 商品保存处理
	 * 
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	@RequestMapping(value="/goods/goodsIntroduction/saveOrUpdate")
	@ResponseBody
	public Object saveOrUpdate () throws IllegalAccessException, InvocationTargetException {
		PageData pd = this.getPageData();
		GoodsInfoVO bean = new GoodsInfoVO();
		String good_id = pd.getString("goodId");
		if(!StringUtils.isEmpty(good_id)) {
			bean.setGoodId(Long.valueOf(good_id));
		}
		BeanUtils.populate(bean, pd);
		
		long rslt = 0L;
		// 新增
		if(StringUtils.isEmpty(good_id)) {
			String uuid = this.get32UUID();
			String realPath = this.getRequest().getSession().getServletContext().getRealPath("");
			StringBuffer urlBuffer = new StringBuffer();
			urlBuffer.append(this.getRequest().getScheme()).append("://");
			urlBuffer.append(this.getRequest().getServerName());
			urlBuffer.append(":" +this.getRequest().getServerPort());
			urlBuffer.append(this.getRequest().getContextPath());
			urlBuffer.append(CREATE_GOODS_ORDER_URL).append(uuid);
			bean.setGoodCode(uuid);
			rslt = goodsIntroductionService.insertGoodsInfo(bean, realPath, urlBuffer.toString());
		// 更新
		} else {
			rslt = goodsIntroductionService.updateGoodsInfo(bean);
		}
		
		if(rslt > 0) {
			Map<String, String> resultMap = new HashMap<String, String>();
			resultMap.put("goodId", String.valueOf(bean.getGoodId()));
			return HttpResult.createSuccessResult(resultMap, "0");
		} else {
			return HttpResult.createErrorResult("创建商品分类失败！", "", "-1");
		}
	}
	
	/**
	 * 根据商品ID 删除商品信息
	 * @return
	 */
	@RequestMapping(value="/goods/goodsIntroduction/del")
	@ResponseBody
	public  Object delete () {
		PageData pd = this.getPageData();
		long rslt = goodsIntroductionService.deleteGoodsInfo(Arrays.asList(pd.getString("goods_id").split(",")));
		if(rslt > 0) {
			return HttpResult.createSuccessResult("", "0");
		} else {
			return HttpResult.createErrorResult("删除商品分类失败！", "", "-1");
		}
	}
	
	/**
	 * 获取全部的商品分类信息
	 * @return 商品分类信息
	 */
	@RequestMapping(value="/goods/goodsIntroduction/getGoodsTypeAll")
	@ResponseBody
	public  Object getGoodsTypeAll() {
		List<GoodsType> goodsTypeList = goodsService.getGoodsTypeAll();
		return HttpResult.createSuccessResult(goodsTypeList, "0");
	}
}
